//
//  TabBarView.m
//  jobClient
//
//  Created by 一览ios on 16/7/15.
//  Copyright © 2016年 YL1001. All rights reserved.
//

#import "TabBarView.h"
#import "RootTabBarViewController.h"
#import "UIImage+GIF.h"
static const float scale= 32.0/49.0;

@interface TabBarButton()

@end

@implementation TabBarButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
//        self.backgroundColor = UIColor.clearColor;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    return self;
}
-(CGRect)imageRectForContentRect:(CGRect)contentRect{
    
    CGFloat newX = 0;
    CGFloat newY = 8;
    CGFloat newWidth = contentRect.size.width;
    CGFloat newHeight = contentRect.size.height*scale-newY;
    return CGRectMake(newX, newY, newWidth, newHeight);
}
- (CGRect)titleRectForContentRect:(CGRect)contentRect{
    
    CGFloat newX = 0;
    CGFloat newY = contentRect.size.height*scale - 2;
    CGFloat newWidth = contentRect.size.width;
    CGFloat newHeight = contentRect.size.height-contentRect.size.height*scale;
    return CGRectMake(newX, newY, newWidth, newHeight);
}

@end

@interface TabBarView ()<UIGestureRecognizerDelegate,NoLoginDelegate>

@property(nonatomic,strong)UIButton *seleBtn;
@property(nonatomic,strong)NSArray *titleArray;
@property(nonatomic,strong)NSArray *imageArray;
@property(nonatomic,strong)NSArray *selImageArray;

@property(nonatomic,strong)NSArray *eventArray;

//注意数组是UIImage.CGImage
@property (nonatomic ,strong)NSMutableArray * imagesArray;//人才端

//注意数组是UIImage.CGImage
//@property (nonatomic ,strong)NSMutableArray * studentImagesArray;//人才端




@end

@implementation TabBarView

#pragma mark--初始化
-(instancetype)initWithFrame:(CGRect)frame controllersNum:(int)num {
    if (self = [super initWithFrame:frame]) {
        [self configUIWithNum:num];
    }
    return self;
}
-(void)configerImageArray{
    
    self.imagesArray = [NSMutableArray array];
    for (int i = 0; i<5; i++) {
        NSMutableArray *images = [NSMutableArray array];
        switch (i) {
            case 0:
                for (int j = 0; j<=14; j++) {
                    NSString *imageName = [NSString stringWithFormat:@"tabBar_xsjob_sel_%d",j];
                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
                }
                break;
            case 1:
                for (int j = 0; j<=14; j++) {
                    NSString *imageName = [NSString stringWithFormat:@"tabBar_guide_sel_%d",j];
                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
                }
                break;
            case 2:
                for (int j = 0; j<=14; j++) {
                    NSString *imageName = [NSString stringWithFormat:@"tabBar_homepage_sel_%d",j];
                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
                }
                break;
            case 3:
                for (int j = 0; j<=14; j++) {
                    NSString *imageName = [NSString stringWithFormat:@"tabBar_news_sel_%d",j];
                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
                }
                break;
            case 4:
                for (int j = 0; j<=14; j++) {
                    NSString *imageName = [NSString stringWithFormat:@"tabBar_me_sel_%d",j];
                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
                }
                break;
            default:
                break;
        }
        [self.imagesArray addObject:images];
    }
    
//    self.studentImagesArray = [NSMutableArray array];
//    for (int i = 0; i<5; i++) {
//        NSMutableArray *images = [NSMutableArray array];
//        switch (i) {
//            case 0:
//                for (int j = 0; j<=14; j++) {
//                    NSString *imageName = [NSString stringWithFormat:@"tabBar_xsjob_sel_%d",j];
//                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
//                }
//                break;
//            case 1:
//                for (int j = 0; j<=14; j++) {
//                    NSString *imageName = [NSString stringWithFormat:@"tabBar_guide_sel_%d",j];
//                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
//                    
//                }
//                break;
//            case 2:
//                for (int j = 0; j<=14; j++) {
//                    NSString *imageName = [NSString stringWithFormat:@"tabBar_news_sel_%d",j];
//                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
//                }
//                break;
//            case 3:
//                for (int j = 0; j<=14; j++) {
//                    NSString *imageName = [NSString stringWithFormat:@"tabBar_xszph_sel_%d",j];
//                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
//                }
//                break;
//            case 4:
//                for (int j = 0; j<=14; j++) {
//                    NSString *imageName = [NSString stringWithFormat:@"tabBar_me_sel_%d",j];
//                    [images addObject:(__bridge UIImage *)[UIImage imageNamed:imageName].CGImage];
//                }
//                break;
//            default:
//                break;
//        }
//        [self.studentImagesArray addObject:images];
//    }
}
#pragma mark--配置UI
-(void)configUIWithNum:(int)num{
    
//        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
//        UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
//        effectView.backgroundColor = EL_TabBarItemBgColor;
//        effectView.frame = self.bounds;
//        effectView.alpha = 0.8;
//        [self insertSubview:effectView atIndex:0];
    
    self.eventArray = @[@"V23news", @"V23Peer",@"V23Jobwanted",@"V23Resume",  @"V23I",];
    self.backgroundColor = EL_TabBarItemBgColor;//EL_TabBarItemBgColor

    
//    NSString *rctypeId = getUserDefaults(@"changeRctypeId");
//    NSLog(@"------>%@",[Manager getUserInfo].userId_);
    
//    if (![rctypeId isEqualToString:@"0"] || StringIsEmpty([Manager getUserInfo].userId_)) {//职场人
//        self.selImageArray = @[@"tabBar_homepage_sel", @"tabBar_guide_sel",  @"tabBar_news_sel",@"tabBar_hangye_sel", @"tabBar_me_sel"];
//        self.imageArray = @[@"tabBar_homepage_def",@"tabBar_guide_def" , @"tabBar_news_def",@"tabBar_hangye_def",  @"tabBar_me_def"];
//    }else{//学生身份
//        self.selImageArray = @[@"tabBar_xsjob_sel", @"tabBar_guide_sel",  @"tabBar_news_sel",@"tabBar_xszph_sel", @"tabBar_me_sel"];
//        self.imageArray = @[@"tabBar_xsjob_def", @"tabBar_guide_def", @"tabBar_news_def",@"tabBar_xszph_def",  @"tabBar_me_def"];
//    }
    
    self.selImageArray = @[ @"tabBar_xsjob_sel", @"tabBar_guide_sel",@"tabBar_homepage_sel", @"tabBar_news_sel", @"tabBar_me_sel"];
    self.imageArray = @[@"tabBar_xsjob_def",@"tabBar_guide_def", @"tabBar_homepage_def",@"tabBar_news_def",  @"tabBar_me_def"];
    
    if (ShowYwApp == 1) {
        self.titleArray = @[@"扎堆", @"人脉", @"找工作", @"消息", @"我的"];
    }else{
//        NSString *rctypeId = getUserDefaults(@"changeRctypeId");
//        if (![rctypeId isEqualToString:@"0"] || StringIsEmpty([Manager getUserInfo].userId_)) {//职场人
//            self.titleArray = @[@"首页", @"职业", @"找工作", @"消息", @"我的"];
//        }else{//学生身份
//            self.titleArray = @[@"职位", @"职业", @"消息", @"招聘会", @"我的"];
//        }
        self.titleArray = @[@"首页", @"职业", @"消息", @"我的"];
        self.selImageArray = @[ @"tabBar_homepage_sel",@"tabBar_xsjob_sel", @"tabBar_news_sel", @"tabBar_me_sel"];
        self.imageArray = @[ @"tabBar_homepage_def",@"tabBar_xsjob_def",@"tabBar_news_def",  @"tabBar_me_def"];
    }
    
    for(int i=0;i<num;i++)
    {
        TabBarButton *button = [[TabBarButton alloc] initWithFrame:CGRectMake(ScreenWidth/num*i, 0, ScreenWidth/num, 50)];
        button.tag = 1000+i;
        
        //常态文字颜色
        [button setTitleColor:EL_TabBarTitleNormalColor forState:UIControlStateNormal];
        //选中文字颜色
        [button setTitleColor:EL_TabBarTitleSelectedColor forState:UIControlStateSelected];
        
        button.titleLabel.font = EL_TabBarTitleFont;
        button.backgroundColor = UIColor.clearColor;
        [button setImage:[UIImage imageNamed:self.imageArray[i]] forState:UIControlStateNormal];
    
//        NSString *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:@"mypointgif.gif" ofType:nil];
//        NSData *imageData = [NSData dataWithContentsOfFile:filePath];
//        UIImage *selectImage = [UIImage sd_imageWithGIFData:imageData];
        
        
        
        [button setImage:[UIImage imageNamed:self.selImageArray[i]] forState:UIControlStateSelected];
    
        [button setTitle:self.titleArray[i] forState:UIControlStateNormal];
        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 2, 0)];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        if (i==0)
        {
            //默认选中
            button.selected = YES;
            self.seleBtn = button;
        }
        if (i >= 0 && i < 3) {
            [self addGesture:button];
        }
        //角标
        UILabel *numLabel = [[UILabel alloc] initWithFrame:CGRectMake(button.frame.size.width/2.0+6, 3, EL_NumBadgeWidth, EL_NumBadgeWidth)];
        numLabel.textColor = EL_TextColorWhite;
        numLabel.textAlignment = NSTextAlignmentCenter;
        numLabel.font = EL_TabBarBadgeTitleFont;
        numLabel.tag = 1010+i;
        numLabel.hidden = YES;
        [button addSubview:numLabel];
    }
    
    [self configerImageArray];
    
}

//取消默认选中
-(void)selectedBtnIdx:(BOOL)isLogin{
    UIButton *button = (UIButton *)[self viewWithTag:1000];
    button.selected = isLogin;
}

#pragma mark--添加双击手势
-(void)addGesture:(UIButton *)button{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
    tap.numberOfTapsRequired = 2;
    tap.delegate = self;
    [button addGestureRecognizer:tap];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark--代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    UIButton *btn = (UIButton *)touch.view;
    if (self.seleBtn.tag == btn.tag){
        return YES;
    }
    else{
        return NO;
    }
}

/*
-(void)loginDelegateCtl
{
    [[Manager shareMgr] loginOut];
    [Manager shareMgr].haveLogin = NO;
}
 */

-(void)loginSuccessResponse{
    
    switch ([NoLoginPromptCtl getNoLoginManager].loginType) {
        case LoginType_MessageCenter:
        {
            [self selectedBtnIdx:self.titleArray.count-2];
        }
            break;
        default:
            break;
    }
     
}

#pragma mark--事件
//手势双击
-(void)tapClick:(UITapGestureRecognizer *)tap{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"statusBarTouchedAction" object:nil];
    UIButton *btn = (UIButton *)[tap view];
    [self showControllerIndex:btn.tag - 1000];
    if ([self.delegate respondsToSelector:@selector(buttonSelectedClick:)]) {
        [self.delegate buttonSelectedClick:btn];
    }
}

//点击tabbar按钮
-(void)buttonAction:(UIButton *)button{
    NSInteger index = button.tag-1000;
    
    NSDictionary *dic = @{@"type":[_titleArray objectAtIndex:index]};
    [MobClick event:[_eventArray objectAtIndex:index] attributes:dic];
    
    if (![Manager shareMgr].haveLogin) {
        if (index == self.titleArray.count-2){//简历和消息
            [[NoLoginPromptCtl noLoginManagerWithDelegate:self] showNoLoginCtlView];
            return;
        }
    }
    
    [self showControllerIndex:index];
    if ([self.delegate respondsToSelector:@selector(buttonSelectedClick:)]) {
        [self.delegate buttonSelectedClick:button];
    }
}

/**
 *  切换显示控制器
 *
 *  @param index 位置
 */
-(void)showControllerIndex:(NSInteger)index
{
    self.seleBtn.selected = NO;
    UIButton *button = (UIButton *)[self viewWithTag:1000+index];
    button.selected = YES;
    self.seleBtn = button;
    
    
//    //职位
//    NSString *rctypeId = getUserDefaults(@"changeRctypeId");
//
//    if (![rctypeId isEqualToString:@"0"] || StringIsEmpty([Manager getUserInfo].userId_)) {//职场人
//        //获取当前的UITabBarButton
//        NSArray *images = self.imagesArray[index];
//
//        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
//        //animation.delegate = self;
//        animation.values = images;
//        animation.duration = 0.6;// images.count * 0.08;
//        animation.calculationMode = kCAAnimationCubic;
//        [self.seleBtn.imageView.layer addAnimation:animation forKey:nil];
//
//    }else{//学生身份
//
//        //获取当前的UITabBarButton
//        NSArray *images = self.studentImagesArray[index];
//
//        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
//        //animation.delegate = self;
//        animation.values = images;
//        animation.duration = 0.6;// images.count * 0.08;
//        animation.calculationMode = kCAAnimationCubic;
//        [self.seleBtn.imageView.layer addAnimation:animation forKey:nil];
//    }
    
    //获取当前的UITabBarButton
    NSArray *images = self.imagesArray[index];
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    //animation.delegate = self;
    animation.values = images;
    animation.duration = 0.6;// images.count * 0.08;
    animation.calculationMode = kCAAnimationCubic;
    [self.seleBtn.imageView.layer addAnimation:animation forKey:nil];
    
    
    
    
    
    
    
    
//#pragma mark -  v6.9.6版本添加点击动画
//    [UIView animateWithDuration:0.5 animations:^{
//
//        button.transform = CGAffineTransformMakeScale(1.8, 1.8);
//        button.transform = CGAffineTransformIdentity;
//
//    } completion:^(BOOL finished) {
//        button.transform = CGAffineTransformIdentity;
//    }];
}


#pragma mark--红点
/**
 *  数字角标
 *
 *  @param num   所要显示数字
 *  @param index 位置
 */
-(void)showBadgeMark:(NSInteger)badge index:(NSInteger)index
{
    UILabel *numLabel = (UILabel *)[self viewWithTag:1010+index];
    numLabel.hidden=NO;
    numLabel.backgroundColor = EL_BadgeBgColor;
    CGRect nFrame = numLabel.frame;
      
    if(badge<=0)
    {
        //隐藏角标
        numLabel.text = nil;
        [self hideMarkIndex:index];
    } else {
        nFrame.size.width = EL_NumBadgeWidth;
        nFrame.size.height = EL_NumBadgeWidth;
        numLabel.frame = nFrame;
        
        if(badge > 99)
        {
            numLabel.text =@"···";
        }else{
            NSInteger num = [numLabel.text integerValue];
            if (num != badge) {
                numLabel.text = [NSString stringWithFormat:@"%ld",(long)badge];
            }
        }
    }

    NSInteger badgeValue = 0;
    for (NSInteger i = 0; i < self.titleArray.count; i++) {
        UILabel *tempLabel = (UILabel *)[self viewWithTag:1010 + i];
        badgeValue += [tempLabel.text integerValue];
    }
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeValue];
}

/**
 *  小红点
 *
 *  @param index 位置
 */
-(void)showPointMark:(NSInteger)mark Index:(NSInteger)index
{
    UILabel *numLabel = (UILabel *)[self viewWithTag:1010+index];
    CGRect nFrame = numLabel.frame;
    nFrame.size.height = EL_NullBadgeWidth;
    nFrame.size.width = EL_NullBadgeWidth;
    numLabel.frame = nFrame;
    numLabel.backgroundColor = EL_BadgeBgColor;
//    numLabel.layer.cornerRadius = PointMark_W_H/2.0;
    numLabel.text = @"";
    if (mark > 0) {
        numLabel.hidden=NO;
    }
    else{
        numLabel.hidden=YES;
    }
}

/**
 *  隐藏指定位置角标
 *
 *  @param index 位置
 */
-(void)hideMarkIndex:(NSInteger)index
{
    UILabel *numLabel = (UILabel *)[self viewWithTag:1010+index];
    numLabel.hidden = YES;
}

@end
